package com.bwie.coupon.service.impl;

import com.bwie.common.core.constant.CacheConstants;
import com.bwie.common.core.utils.StringUtils;
import com.bwie.common.redis.service.RedisService;
import com.bwie.common.security.service.TokenService;
import com.bwie.common.security.utils.SecurityUtils;
import com.bwie.coupon.domain.po.MlCoupon;
import com.bwie.coupon.domain.po.MlCouponPreferential;
import com.bwie.coupon.mapper.MlCouponMapper;
import com.bwie.coupon.mapper.MlUserCouponMapper;
import com.bwie.coupon.service.MlCouponService;
import com.bwie.coupon.service.MlUserCouponService;
import com.bwie.system.api.model.LoginUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;


@Service
public class MlUserCouponServiceImpl implements MlUserCouponService {

    @Autowired
    private MlUserCouponMapper mlUserCouponMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MlCouponService mlCouponService;     //service 调用service 复用性强 可扩展性 和 灵活性

    @Autowired
    private MlCouponMapper mlCouponMapper;


    /**
     * 用户领取优惠卷
     *
     * @return
     */
    @Override
    public void mlUserCouponAdd(Integer mlCouponId) {

        //判断优惠卷id是否为空
        if (mlCouponId == null) {
            throw new RuntimeException("优惠卷id为空");
        }
        //  Authorization
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new RuntimeException("恭喜你报错了,没有获取到用户信息");
        }
        Long userid = loginUser.getUserid();

        //根据优惠卷id
        MlCoupon mlCoupon = mlCouponMapper.selectMlCouponById(mlCouponId);
        //判断优惠卷数量
        if(mlCoupon.getCouponGross()<=0){
            throw new RuntimeException("优惠卷数量不足");
        }

        //根据用户id  查询优惠卷 不可以 多次领取
        MlCouponPreferential couponFind = mlUserCouponMapper.selectMlUserCouponFind(userid, mlCouponId);
        //判断
        if (couponFind != null) {
            throw new RuntimeException("已经领取过了,不能重复领取");
        }
        //添加中间表
        mlUserCouponMapper.mlUserCouponAdd(userid, mlCouponId);

        //每次领取之后优惠券表中发送总数减一
        mlCouponService.updateCouponCountNum(mlCouponId);
    }
}
